package net.jxtz.jxtzos.controller.achievements;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.achievements.Achievement;
import net.jxtz.jxtzos.entity.web.R;
import net.jxtz.jxtzos.service.achievement.AchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author a123
 */
@RequestMapping("/achievements")
@CrossOrigin
@RestController
@Slf4j
public class AchievementsController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R add(@RequestBody Achievement achievement){
        boolean save = achievementService.save(achievement);
        return save? R.ok().data("achieve", achievement): R.error();
    }

    @Transactional
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R delete(@PathVariable Long id){
        boolean fatherId = achievementService.remove(new QueryWrapper<Achievement>().eq("father_id", id));
        boolean b = achievementService.removeById(id);
        return b && fatherId ? R.ok():R.error();
    }

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public R getList(){
        List<Achievement> list = achievementService.list();
        return R.ok().data("list", list);
    }

    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public R getList(@RequestParam("id") Long id){
        Achievement achievement = achievementService.getById(id);
        return R.ok().data("byId", achievement);
    }

    @RequestMapping(value = "/getInitList", method = RequestMethod.GET)
    public R initList(){
        List<Achievement> achievements = achievementService.initTree();
        return R.ok().data("list",achievements);
    }

    @RequestMapping(value = "/getListByFatherId/{id}", method = RequestMethod.GET)
    public R getListByFatherId(@PathVariable Long id){
        List<Achievement> fatherId = achievementService.list(new QueryWrapper<Achievement>().eq("father_id", id));
        return R.ok().data("list", fatherId);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public R update(@RequestBody Achievement achievement){
        log.info("achievement ==> " + achievement.toString());
        boolean b = achievementService.updateById(achievement);
        return b? R.ok():R.error();
    }

    private final AchievementService achievementService;

    @Autowired
    public AchievementsController(AchievementService achievementService){
        this.achievementService = achievementService;
    }

}
